import React, { useState, useEffect, useContext, useRef } from "react";
import { Modal, Table, Button, Spin } from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  searchFlights,
  type FlightOption,
  type FlightSearchRequest,
} from "../../services/apiService";
import { MessageContext } from "../../App";
import { useTranslation } from 'react-i18next';

interface FlightSelectionModalProps {
  visible: boolean;
  nodeId: string;
  nodeLabel: string;
  loading: boolean;
  searchParams?: FlightSearchRequest;
  nodeData?: any; // STOPPED节点返回的数据
  onProceed: (flightInfo: string, nodeId: string, selectedFilght: FlightOption, flightList: FlightOption[]) => void;
  onReject: (nodeId: string) => void;
  onCancel: () => void;
}

const airports = [
  // 一线城市及热门国际城市
  { value: "bjs", label: "北京 (BJS)" },
  { value: "sha", label: "上海 (SHA)" },
  { value: "can", label: "广州 (CAN)" },
  { value: "ctu", label: "成都 (CTU)" },
  { value: "szx", label: "深圳 (SZX)" },
  { value: "kmg", label: "昆明 (KMG)" },

  // 国际城市
  { value: "sel", label: "首尔 (SEL)" },
  { value: "bkk", label: "曼谷 (BKK)" },
  { value: "sgn", label: "胡志明市 (SGN)" },
  { value: "mnl", label: "马尼拉 (MNL)" },
  { value: "kul", label: "吉隆坡 (KUL)" },
  { value: "sin", label: "新加坡 (SIN)" },

  // ✅ 成都及周边城市（新增）
  { value: "ckg", label: "重庆 (CKG)" },
  { value: "xiy", label: "西安 (XIY)" },
  { value: "daz", label: "达州 (DAX)" },
  { value: "zgn", label: "自贡 (ZGN)" },
];
const FlightSelectionModal: React.FC<FlightSelectionModalProps> = ({
  visible,
  nodeId,
  nodeLabel,
  loading,
  nodeData,
  onProceed,
  onReject,
  onCancel,
}) => {
  const [flights, setFlights] = useState<FlightOption[]>([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const message = useContext(MessageContext);
  const { t } = useTranslation();

  // 从nodeData中提取搜索参数，转换中文字段名到英文
  const getSearchParamsFromNodeData = (
    data: any,
  ): FlightSearchRequest | null => {
    if (!data) {
      return null;
    }

    let actualData = null;

    // 优先从 extractedData 中获取数据（新的数据结构）
    if (data.extractedData) {
      actualData = data.extractedData;
    }
    // 备用：从 input.messages 中获取数据
    else if (data.input && data.input.messages) {
      const userInfoMessage = data.input.messages.find(
        (msg: any) => msg.name === "用户信息提取",
      );
      if (userInfoMessage && userInfoMessage.content) {
        actualData = userInfoMessage.content;
      }
    }
    // 备用：直接使用 data 作为数据
    else {
      actualData = data;
    }

    if (!actualData) {
      return null;
    }

    let parsedData;

    // 解析nodeData，可能是字符串或对象
    if (typeof actualData === "string") {
      try {
        // 如果 data 是字符串，去除 } 后面的所有内容
        const idx = actualData.indexOf("}");
        if (idx !== -1) {
          actualData = actualData.slice(0, idx + 1);
        }
        parsedData = JSON.parse(actualData);
      } catch (error) {
        console.error("Failed to parse data:", error);
        return null;
      }
    } else if (typeof actualData === "object" && actualData !== null) {
      // 如果已经是对象，直接使用
      parsedData = actualData;
    } else {
      return null;
    }

    if (!parsedData) {
      return null;
    }

    // 检查是否包含必要的航班信息
    const departure = parsedData["出发地"] || parsedData.departure;
    const destination = parsedData["目的地"] || parsedData.destination;
    const departDate = parsedData["出发时间"] || parsedData.departDate;
    const returnDate = parsedData["返回时间"] || parsedData.returnDate;

    // 如果缺少必要信息，返回null
    if (!departure || !destination || !departDate || !returnDate) {
      return null;
    }

    // 城市名称映射到机场代码，使用airports映射表
    const cityToAirportCode = (cityName: string): string => {
      // 在airports数组中查找匹配的城市名称
      const airport = airports.find(
        (item) =>
          item.label.includes(cityName) ||
          item.value.toUpperCase() === cityName.toUpperCase(),
      );

      if (airport) {
        return airport.value.toUpperCase();
      }

      // 如果没找到，返回原始值（可能已经是机场代码）
      return cityName.toUpperCase();
    };

    return {
      departure: cityToAirportCode(departure),
      destination: cityToAirportCode(destination),
      tripType: "roundtrip",
      departDate: departDate,
      returnDate: returnDate,
      directFlight: true,
      adults: 1,
      children: 1,
      infants: 1,
    };
  };
  const prevVisible = useRef(false);

  useEffect(() => {
    if (visible && !prevVisible.current) {
      prevVisible.current = true;
      if (
        nodeData &&
        nodeData.cachedFlights &&
        Array.isArray(nodeData.cachedFlights)
      ) {
        setFlights(nodeData.cachedFlights);
        setSearchLoading(false);
      } else {
        searchForFlights(getSearchParamsFromNodeData(nodeData));
      }
    }
    if (!visible) {
      prevVisible.current = false;
    }
  }, [visible]);

  const searchForFlights = async (searchParams: FlightSearchRequest | null) => {
    if (!searchParams) {
      message.error(t('flightModal.missingSearchParams'));
      return;
    }

    setSearchLoading(true);
    try {
      const response = await searchFlights(searchParams);
      if (response.success && response.data.flights) {
        const _flights = response.data.flights
        _flights.push({
          itineraryId: "0",
          priceIndex: 0,
          transferCount: 0,
          crossDays: 0,
          outboundFlight: {
            baggageInfo: "",
            flightNumber: t('flightModal.noFlight'),
            airline: "",
            departureTime: "",
            arrivalTime: "",
            duration: "",
            departureAirport: "",
            arrivalAirport: "",
            departureCity: "",
            arrivalCity: "",
            currency: "",
            arrivalCity_lang: "",
            departureCity_lang: "",
            airline_lang: "",
            duration_lang: "",
            baggageInfo_lang: "",
            flightNumber_lang: ""
          },
          returnFlight: {
            flightNumber: t('flightModal.noFlight'),
            airline: "",
            departureTime: "",
            arrivalTime: "",
            duration: "",
            departureAirport: "",
            arrivalAirport: "",
            departureCity: "",
            arrivalCity: "",
            currency: "",
            arrivalCity_lang: "",
            departureCity_lang: "",
            airline_lang: "",
            duration_lang: "",
            flightNumber_lang: ""
          },
          totalDuration: "",
          adultTotalPrice: 0,
          childTotalPrice: 0,
          infantTotalPrice: 0,
          currency: "",
          ticketCount: 0
        })
        setFlights(_flights.reverse());
      } else {
        message.error(t('flightModal.searchFailed'));
      }
    } catch (error) {
      console.error("航班搜索错误:", error);
      message.error(t('flightModal.searchFailed'));
    } finally {
      setSearchLoading(false);
    }
  };

  const handleCancel = () => {
    onReject(nodeId);
  };

  const handleSelectFlight = () => {
    if (selectedRowKeys.length === 0) {
      message.warning(t('flightModal.pleaseSelectFlight'));
      return;
    }

    const selectedKey = selectedRowKeys[0] as string;
    const selectedFlight = flights.find(
      (flight) =>
        `${flight.outboundFlight.flightNumber}_${flight.returnFlight.flightNumber}` ===
        selectedKey,
    );
    if (selectedFlight) {
      // 构建航班信息Markdown字符串
      const flightInfo = selectedFlight.itineraryId === "0" ? `## ${t('flightModal.selectNoFlight')}` : `
## ${t('flightModal.flightConfirmation')}

### 🛫 ${t('flightModal.outboundFlight')}
- **${t('flightModal.flightNumber')}：** ${selectedFlight.outboundFlight.flightNumber}
- **${t('flightModal.departure')}：** ${selectedFlight.outboundFlight.departureTime} ${selectedFlight.outboundFlight.departureCity}(${selectedFlight.outboundFlight.departureAirport})
- **${t('flightModal.arrival')}：** ${selectedFlight.outboundFlight.arrivalTime} ${selectedFlight.outboundFlight.arrivalCity}(${selectedFlight.outboundFlight.arrivalAirport})
- **${t('flightModal.duration')}：** ${selectedFlight.outboundFlight.duration}
- **${t('flightModal.airline')}：** ${selectedFlight.outboundFlight.airline}

### 🛬 ${t('flightModal.returnFlight')}
- **${t('flightModal.flightNumber')}：** ${selectedFlight.returnFlight.flightNumber}
- **${t('flightModal.departure')}：** ${selectedFlight.returnFlight.departureTime} ${selectedFlight.returnFlight.departureCity}(${selectedFlight.returnFlight.departureAirport})
- **${t('flightModal.arrival')}：** ${selectedFlight.returnFlight.arrivalTime} ${selectedFlight.returnFlight.arrivalCity}(${selectedFlight.returnFlight.arrivalAirport})
- **${t('flightModal.duration')}：** ${selectedFlight.returnFlight.duration}
- **${t('flightModal.airline')}：** ${selectedFlight.returnFlight.airline}

### 💰 ${t('flightModal.priceInfo')}
| ${t('flightModal.passengerType')} | ${t('flightModal.price')} |
|---------|-----|
| ${t('flightModal.adult')} | ¥${selectedFlight.adultTotalPrice} |
| ${t('flightModal.child')} | ¥${selectedFlight.childTotalPrice} |
| ${t('flightModal.infant')} | ¥${selectedFlight.infantTotalPrice} |

### ✈️ ${t('flightModal.baggageInfo')}
${selectedFlight.outboundFlight.baggageInfo}
      `;

      onProceed(flightInfo.trim(), nodeId, selectedFlight, flights);
    }
  };

  const columns: ColumnsType<FlightOption> = [
    {
      title: t('flightModal.flightInfo'),
      key: "flightInfo",
      render: (_, record) => (
        <div>
          <div>
            <strong>{t('flightModal.outbound')}:</strong> {record.outboundFlight.flightNumber_lang}
          </div>
          <div style={{ fontSize: "12px", color: "#666" }}>
            {record.outboundFlight.departureTime} -{" "}
            {record.outboundFlight.arrivalTime}
          </div>
          <div style={{ fontSize: "12px", color: "#666" }}>
            {record.outboundFlight.departureCity_lang} →{" "}
            {record.outboundFlight.arrivalCity_lang}
          </div>
          <div style={{ marginTop: "8px" }}>
            <strong>{t('flightModal.return')}:</strong> {record.returnFlight.flightNumber_lang}
          </div>
          <div style={{ fontSize: "12px", color: "#666" }}>
            {record.returnFlight.departureTime} -{" "}
            {record.returnFlight.arrivalTime}
          </div>
          <div style={{ fontSize: "12px", color: "#666" }}>
            {record.returnFlight.departureCity_lang} →{" "}
            {record.returnFlight.arrivalCity_lang}
          </div>
        </div>
      ),
    },
    {
      title: t('flightModal.flightDuration'),
      key: "duration",
      render: (_, record) => (
        <div>
          <div>{t('flightModal.outbound')}: {record.outboundFlight.duration_lang}</div>
          <div>{t('flightModal.return')}: {record.returnFlight.duration_lang}</div>
        </div>
      ),
    },
    {
      title: t('flightModal.priceInfo'),
      key: "price",
      render: (_, record) => {
        const totalAdult = record.adultTotalPrice
        const totalChild = record.childTotalPrice
        const totalInfant = record.infantTotalPrice

        return (
          <div>
            <div>{t('flightModal.adult')}: ¥{totalAdult}</div>
            <div>{t('flightModal.child')}: ¥{totalChild}</div>
            <div>{t('flightModal.infant')}: ¥{totalInfant}</div>
          </div>
        );
      },
    },
    {
      title: t('flightModal.airline'),
      key: "airline",
      render: (_, record) => (
        <div>
          <div>{record.outboundFlight.airline_lang}</div>
          <div style={{ fontSize: "12px", color: "#666" }}>
            {record.outboundFlight.baggageInfo_lang}
          </div>
        </div>
      ),
    },
  ];

  const rowSelection = {
    type: "radio" as const,
    selectedRowKeys,
    onChange: (selectedKeys: React.Key[]) => {
      setSelectedRowKeys(selectedKeys);
    },
  };

  return (
    <Modal
      title={t('flightModal.title')}
      open={visible}
      onCancel={onCancel}
      width={800}
      footer={[
        <Button
          key="confirm"
          type="primary"
          onClick={handleSelectFlight}
          disabled={selectedRowKeys.length === 0 || loading}
        >
          {t('flightModal.confirmSelection')}
        </Button>,
        <Button key="cancel" onClick={handleCancel}>
          {t('flightModal.useDefaultFlight')}
        </Button>,
        <Button type="link" key="dismiss" onClick={onCancel}>
          {t('flightModal.cancel')}
        </Button>,
      ]}
      closable={false}
      maskClosable={false}
    >
      <div style={{ marginBottom: "16px" }}>
        <p>{t('flightModal.selectFlightPrompt')}</p>
      </div>

      <Spin spinning={searchLoading} tip={t('flightModal.searchingFlights')}>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={flights}
          rowKey={(record) =>
            `${record.outboundFlight.flightNumber}_${record.returnFlight.flightNumber}`
          }
          pagination={false}
          scroll={{ y: 400 }}
          size="small"
        />
      </Spin>
    </Modal>
  );
};

export default FlightSelectionModal;
